package cn.com.anypay.manager.payment.manager;

import cn.com.anypay.manager.payment.core.IPaymentChannel;
import cn.com.anypay.manager.payment.core.PaymentException;
import cn.com.anypay.manager.payment.factory.PaymentChannelFactory;
import cn.com.anypay.manager.payment.factory.PaymentProductFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.DisposableBean;

/**
 * 支付管理器 - 统一管理所有支付相关组件的生命周期
 *
 * 职责：
 * 1. 统一管理 ProductFactory、ChannelFactory、ChannelManager
 * 2. 控制组件初始化顺序
 * 3. 提供统一的访问接口
 * 4. 管理组件生命周期
 *
 * @author AnyPay Team
 * @version 1.0
 * @since 2025-01-24
 */
@Component
public class PaymentManager implements InitializingBean, DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(PaymentManager.class);

    // 核心组件 - 不再使用@Component注解，由PaymentManager管理
    private final PaymentProductFactory productFactory;
    private final PaymentChannelFactory channelFactory;
    private final PaymentChannelManager channelManager;

    // 初始化状态
    private volatile boolean initialized = false;
    private final Object initLock = new Object();

    public PaymentManager() {
        logger.debug("创建PaymentManager实例");

        // 按顺序创建组件，确保依赖关系正确
        this.productFactory = new PaymentProductFactory();
        this.channelFactory = new PaymentChannelFactory();
        this.channelManager = new PaymentChannelManager(productFactory); // 注入productFactory

        logger.debug("PaymentManager实例创建完成");
    }

    /**
     * 初始化所有组件
     * Spring容器完成依赖注入后调用
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        synchronized (initLock) {
            if (initialized) {
                logger.warn("PaymentManager already initialized");
                return;
            }

            logger.info("=== PaymentManager 开始初始化 ===");

            try {
                // 1. 初始化产品工厂
                initializeProductFactory();

                // 2. 初始化渠道工厂
                initializeChannelFactory();

                // 3. 初始化渠道管理器
                initializeChannelManager();

                // 4. 注册测试渠道
                registerTestChannels();

                initialized = true;
                logger.info("=== PaymentManager 初始化完成 ===");

            } catch (Exception e) {
                logger.error("PaymentManager 初始化失败", e);
                throw new RuntimeException("Failed to initialize PaymentManager", e);
            }
        }
    }

    /**
     * 销毁所有组件
     */
    @Override
    public void destroy() {
        synchronized (initLock) {
            if (!initialized) {
                return;
            }

            logger.info("=== PaymentManager 开始销毁 ===");

            try {
                // 按相反顺序销毁
                channelManager.destroy();
                channelFactory.destroy();
                productFactory.destroy();

                initialized = false;
                logger.info("=== PaymentManager 销毁完成 ===");

            } catch (Exception e) {
                logger.error("PaymentManager 销毁失败", e);
            }
        }
    }

    // === 私有初始化方法 ===

    private void initializeProductFactory() {
        logger.debug("初始化 PaymentProductFactory");
        productFactory.initialize(); // 不再依赖InitializingBean
        logger.debug("PaymentProductFactory 初始化完成");
    }

    private void initializeChannelFactory() {
        logger.debug("初始化 PaymentChannelFactory");
        channelFactory.initialize();
        logger.debug("PaymentChannelFactory 初始化完成");
    }

    private void initializeChannelManager() {
        logger.debug("初始化 PaymentChannelManager");
        channelManager.initialize();
        logger.debug("PaymentChannelManager 初始化完成");
    }

    private void registerTestChannels() {
        logger.debug("注册测试渠道");

        try {
            // 创建并注册测试渠道1的impl1实现
            IPaymentChannel channel1Impl1 = channelFactory.createChannelImplementation("channeltest1", "impl1", null);
            channelManager.registerChannelImplementation("channeltest1", "impl1", channel1Impl1);

            // 创建并注册测试渠道1的impl2实现
            IPaymentChannel channel1Impl2 = channelFactory.createChannelImplementation("channeltest1", "impl2", null);
            channelManager.registerChannelImplementation("channeltest1", "impl2", channel1Impl2);

            // 创建并注册测试渠道2的default实现
            IPaymentChannel channel2Default = channelFactory.createChannelImplementation("channeltest2", "default", null);
            channelManager.registerChannelImplementation("channeltest2", "default", channel2Default);

            logger.info("测试渠道注册完成，已注册 {} 个渠道", channelManager.getChannelCount());

        } catch (Exception e) {
            logger.error("注册测试渠道失败", e);
            throw new RuntimeException("Failed to register test channels", e);
        }
    }

    // === 公共访问接口 ===

    public PaymentProductFactory getProductFactory() {
        checkInitialized();
        return productFactory;
    }

    public PaymentChannelFactory getChannelFactory() {
        checkInitialized();
        return channelFactory;
    }

    public PaymentChannelManager getChannelManager() {
        checkInitialized();
        return channelManager;
    }

    public boolean isInitialized() {
        return initialized;
    }

    private void checkInitialized() {
        if (!initialized) {
            throw new IllegalStateException("PaymentManager not initialized");
        }
    }

    // === 便利方法 ===

    /**
     * 获取渠道信息
     */
    public PaymentChannelManager.ChannelInfo getChannelInfo(String channelId) {
        return getChannelManager().getChannelInfo(channelId);
    }

    /**
     * 获取所有渠道信息
     */
    public PaymentChannelManager.ChannelInfo[] getAllChannelInfo() {
        return getChannelManager().getAllChannelInfo();
    }

    /**
     * 获取可用渠道
     */
    public IPaymentChannel getAvailableChannel(String channelId) throws PaymentException {
        return getChannelManager().getAvailableChannel(channelId);
    }

    /**
     * 获取所有可用渠道ID
     */
    public String[] getAvailableChannelIds() {
        return getChannelManager().getAvailableChannelIds();
    }

    /**
     * 检查渠道是否可用
     */
    public boolean isChannelAvailable(String channelId) {
        return getChannelManager().isChannelAvailable(channelId);
    }

    /**
     * 获取渠道数量
     */
    public int getChannelCount() {
        return getChannelManager().getChannelCount();
    }

    /**
     * 获取增强的渠道信息
     */
    public PaymentChannelManager.EnhancedChannelInfo[] getAllEnhancedChannelInfo() {
        return getChannelManager().getAllEnhancedChannelInfo();
    }

    /**
     * 获取所有渠道实现信息（按注册顺序）
     */
    public PaymentChannelManager.ChannelImplementationInfo[] getAllChannelImplementationInfoInOrder() {
        return getChannelManager().getAllChannelImplementationInfoInOrder();
    }
}